<?php

namespace app\service;

use app\core\exception\BusinessException;
use app\core\Service;
use app\model\Bank;
use app\model\Member;
use app\model\Withdraw;
use think\facade\Db;

/**
 * @extends Service<WithdrawService>
 */
class WithdrawService extends Service
{
    public function getList($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['member_id'])) {
            $w[] = ['member_id', '=', $searchQuery['member_id']];
        }
        if (!empty($searchQuery['mobile'])) {
            $memberInfo = MemberService::invoke()->getMemberByMobile($searchQuery['mobile']);
            $w[] = ['member_id', '=', $memberInfo['member_id']];
        }

        if (!empty($searchQuery['type'])) {
            $w[] = ['type', '=', $searchQuery['type']];
        }
        if (!empty($searchQuery['status'])) {
            $w[] = ['status', '=', $searchQuery['status']];
        }
        if (!empty($searchQuery['create_time'])) {
            $time_arr = explode("#", $searchQuery['create_time']);
            if (count($time_arr) > 0) {
                $w[] = ['create_time', 'between', $time_arr];
            }
        }
        $map = Withdraw::where($w)->page($page, $limit)->order('id desc');
        $list = $map->select()->toArray();
        if ($list) {
            $bank_ids = array_column($list, 'bank_id');
            $bank_list = (new Bank())->where('id', 'in', $bank_ids)->select()->toArray();
            $bank_list = array_column($bank_list, null, 'id');
            foreach ($list as &$value) {
                if ($value['bank_id'] && !empty($bank_list)) {
                    $value['image'] = $bank_list[$value['bank_id']]['image'] ?: '';
                    $value['name'] = $bank_list[$value['bank_id']]['name'] ?: '';
                    $value['bank_open'] = $bank_list[$value['bank_id']]['bank_open'] ?: '';
                    $value['bank_card'] = $bank_list[$value['bank_id']]['bank_card'] ?: '';
                    $value['bank_branch'] = $bank_list[$value['bank_id']]['bank_branch'] ?: '';
                    $value['mobile'] = $bank_list[$value['bank_id']]['mobile'] ?: '';
                } else {
                    $value['bank_open'] = '';
                    $value['bank_card'] = '';
                    $value['bank_branch'] = '';
                    $value['image'] = '';
                    $value['mobile'] = '';
                }
            }
        }

        return [
            'total' => $map->count(),
            'list' => $list,
        ];
    }

    public function info($id)
    {

        $info = Withdraw::where(
            'id', '=', $id)->find();

        if (!$info) {
            throw new BusinessException('提现信息不存在');
        }

        $bankInfo = (new Bank())->where(['id' => $info['bank_id']])->find();
        $info['bank_info'] = $bankInfo;
        return $info;
    }

    public function save($data, $member_id)
    {
        $info = Member::where([
            'member_id' => $member_id
        ])->find();
        if (!$info) {
            throw new BusinessException('用户不存在');
        }
        if ($data['type'] != 1 && $data['type'] != 2 && $data['type'] != 3) {//1-支付宝 2-微信 3-银行卡
            throw new BusinessException('提现类型错误');
        }

        if ($data['type'] == 1 || $data['type'] == 2) {
            $bankInfo = (new Bank())->where(['type' => $data['type'], 'member_id' => $member_id])->find();
            if (!$bankInfo) {
                // throw new BusinessException('提现错误');
                return ['type' => $data['type'], 'is_bank' => false];
            }
            $bankInfo = $bankInfo->toArray();
            $data['bank_id'] = $bankInfo['id'];
        }
        if ($info['amount'] < $data['money']) {
            throw new BusinessException('提现金额超过可提现佣金');
        }
        $amount = $info['amount'] - $data['money'];
        $pay_amount = $info['pay_amount'] + $data['money'];
        Db::startTrans();
        $rs = $info->save(['amount' => $amount, 'pay_amount' => $pay_amount]);
        if (!$rs) {
            Db::rollback();
            throw new BusinessException('更新可提现佣金失败');
        }
        $rs = Withdraw::create([
            'member_id' => $member_id,
            'money' => $data['money'],
            'type' => $data['type'],
            'status' => 1,
            'bank_id' => $data['bank_id'],
        ]);
        if (!$rs) {
            Db::rollback();
            throw new BusinessException('新增提现记录失败');
        }
        Db::commit();
        return ['type' => $data['type'], 'is_bank' => true];
    }

    public function update($data, $id)
    {
        Db::startTrans();
        try {
            $info = Withdraw::where([
                'id' => $id
            ])->find();
            if (!$info) {
                throw new BusinessException('提现信息不存在');
            }
            $info->save([
                'status' => $data['status'],
                'remark' => !empty($data['remark']) ? $data['remark'] : '',
            ]);
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

}